from flask import Flask, render_template, send_from_directory
import os
from form import ImageUpload
from werkzeug.utils import secure_filename
import uuid


def random_filename(filename):
    ext = os.path.splitext(filename)[1]
    new_filename = uuid.uuid4().hex + ext
    return new_filename


app = Flask(__name__)
app.secret_key = '123$%^9'

app.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024
app.config['UPLOAD_PATH'] = 'uploads'
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif', '.bmp', 'jpeg']  # 设置允许文件上传的后缀


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    form = ImageUpload()
    if form.validate_on_submit():
        f = form.photo.data  # <FileStorage: '201707051607026747_small.jpg' ('image/jpeg')>
        # 我们可以使用Werkzeug提供的secure_filename（）函数对文件名进行过滤，传递文件名作为参数，它会过滤掉所有危险字符，返回安全的文件名
        """
        >>> from werkzeug import secure_filename
        >>> secure_filename('avatar!@#//#\\%$^&.jpg')
        'avatar.jpg'
        >>> secure_filename('avatar头像.jpg')
        'avatar.jpg'
        """
        # 方案一：使用安全文件名
        filename = secure_filename(f.filename)
        # 方案二：使用随机生成文件名
        # filename = random_filename(f.filename)
        file_ext = os.path.splitext(filename)[-1]  # 文件后缀
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            return "<h3>不支持的文件类型，后缀名必须是：['.jpg', '.png', '.gif', '.bmp', 'jpeg']其中之一</h3>", 400
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return render_template('upload_image.html', form=form)


@app.route('/show')
def show_images():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('show.html', files=files)


@app.errorhandler(404)
def page_not_found(e):
    return "Page Not Found", 404


@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)


if __name__ == '__main__':
    app.run()
